<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../../styles/prod.scss";

.upload-df {
  vertical-align: top;
  margin-right: 10px;
}

.upload-img {
  padding: 0;
}
</style>
<template>
  <!-- 产品档案 -->
  <div class="app-container calendar-list-container">
    <div class="pds-tip-green" v-if="page=='normal'">
      <p>选择产品小类：
        <el-cascader
          :options="productCategory"
          :props="{value:'id'}"
          v-model="detail.pdsConfCategoryArray"
          @change="categoryChanged"
        ></el-cascader>
        <el-select v-model="detail.standard">
          <el-option
            v-for="item in [{labelEnUs:'EnStandard',labelZhCh:'欧标',value:1},{labelEnUs:'UsStandard',labelZhCh:'美标',value:2}]"
            :label="language=='en'?item.labelEnUs:item.labelZhCh"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="search.importType" placeholder="请选择">
          <el-option
            v-for="item in [{labelZhCh:'产品策划书',labelEnUs:'产品策划书',value:1},{labelZhCh:'参考型号',labelEnUs:'参考型号',id:2}]"
            :key="item.value"
            :label="language=='en'?item.labelEnUs:item.labelZhCh"
            :value="item.labelZhCh"
          ></el-option>
        </el-select>
        <el-input
          style="width: 200px;"
          class="filter-item"
          placeholder="请输入"
          v-model="search.context"
        ></el-input>
        <el-button
          class="filter-item"
          type="success"
          icon="search"
          @click="importModel()"
          size="small"
        >导入</el-button>
      </p>
    </div>
    <!-- {{detail}} -->
    <div class="pds-tip-green" v-if="page=='trans'">
      <p>选择主机型号：
        <el-input
          style="width: 200px;"
          class="filter-item"
          placeholder="请输入"
          v-model="search.plmModelNoMain"
        ></el-input>
        <el-button
          class="filter-item"
          type="primary"
          icon="search"
          @click="modelExtends()"
          size="small"
        >型号继承</el-button>
      </p>
    </div>
    <!-- 基本属性 -->
    <custom-card title="基本信息" class="mt-30">
      <template>
        <basic-form
          :basicInfo="basicForm"
          :ruleForm="detail.pdsFileModelBaseDto"
          ref="basicForm"
          :lang="language"
        ></basic-form>
      </template>
    </custom-card>

    <!-- 销售区域 -->
    <custom-card title="销售区域/国家" class="mt-30">
      <template>
        <el-form label-width="140px" class="mt-20">
          <el-form-item label="请选择：">
            <el-checkbox-group v-model="detail.pdsFileModelSaleAreasArray">
              <el-checkbox
                border
                v-for="option in countryList"
                :key="option.id"
                :label="option.value"
              >{{language=='en'?option.labelEnUs:option.labelZhCh}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              style="width:60%"
              v-model="detail.pdsFileModelBaseDto.salesAreaRemark"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
    </custom-card>

    <prod-file ref="prodfile" :standard="detail.standard"></prod-file>
    <div class="pds-btm mt-30">
      <div class="right">
        <el-button
          class="filter-item"
          type="primary"
          @click="submitForm('save')"
          :loading="loading"
        >提交</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import BasicForm from "@/components/BasicForm/index";
import * as baseApi from "@/api/common/index";
import * as addApi from "@/api/product/model/add";
import CustomCard from "@/components/CustomCard/index";
import * as prodApi from "@/api/product/index";
import ProdFile from "@/components/Product/prodFile";

export default {
  name: "user",
  components: {
    BasicForm,
    CustomCard,
    ProdFile
    // 'depart-selector': () =>
    //   import ('./components/departSelector')
  },
  data() {
    return {
      page: "",
      countryList: [],
      loading: false,
      detail: {},
      search: {
        context: "",
        importType: "参考型号"
      },
      modelPbsId: "",
      basicForm: [
        {
          label: "product.model.plmModelNo",
          unit: "",
          element: "input",
          name: "plmModelNo",
          type: "",
          isRequired: true
        },
        {
          label: "product.model.modelNo",
          unit: "",
          element: "input",
          name: "modelNo",
          type: "",
          isRequired: true
        },
        {
          label: "product.model.planningNo",
          unit: "",
          element: "input",
          name: "planningNo",
          type: "",
          isRequired: true
        },
        {
          label: "product.model.name",
          unit: "",
          element: "input",
          name: "name",
          type: "",
          isRequired: true
        },
        {
          label: "product.model.marketPosition",
          unit: "",
          name: "marketPositionDv",
          element: "select",
          dictCode: "prod_file_market_pos",
          type: "",
          isRequired: true,
          options: []
        },
        {
          label: "product.model.brand",
          unit: "",
          element: "select",
          name: "brandDv",
          dictCode: "prod_file_brand",
          type: "",
          isRequired: false
        },
        {
          label: "product.model.life",
          unit: "",
          element: "input",
          name: "life",
          append: "小时",
          type: "number",
          isRequired: true
        },
        {
          label: "product.model.bizModel",
          unit: "",
          element: "select",
          dictCode: "prod_file_biz_model",
          name: "bizModelDv",
          type: "",
          isRequired: true
        },
        {
          label: "product.model.recommend",
          unit: "",
          element: "input",
          name: "recommend",
          type: "",
          isRequired: false
        },
        {
          label: "product.model.confCertCategory",
          unit: "",
          element: "select",
          append: "",
          name: "pdsConfCertCategoryArray",
          type: "multiple",
          // value:'value',
          isRequired: true
        },
        {
          label: "product.model.salesYear",
          unit: "",
          element: "datePicker",
          format: "yyyy",
          name: "salesYear",
          type: "year",
          isRequired: true
        },
        {
          label: "product.model.customerId",
          unit: "",
          element: "selectFilter",
          options: [],
          name: "customerIds",
          isMultiple: true,
          type: "filter",
          // rules: { required: true, type: 'array' },
          isRequired: false
        },
        {
          label: "product.model.patent",
          unit: "",
          element: "input",
          name: "patent",
          type: "",
          isRequired: false
        },
        {
          label: "product.model.productStatus",
          unit: "",
          element: "select",
          dictCode: "prod_file_pro_status",
          name: "productStatusDv", // 0=策划，1=立项，2=销售，3=退市)(字典值) ,
          isRequired: true
        },
        {
          label: "product.model.name",
          unit: "",
          element: "textarea",
          name: "remark",
          type: "",
          isRequired: false
        },
        {
          label: "product.model.fileModelPbsPics",
          unit: "",
          element: "upload",
          type: "",
          name: "pdsFileModelPbsPicsList",
          isRequired: true
        }
      ],
      productCategory: []
    };
  },
  activated() {
    this.page =
      this.$route.path === "/product/archives/model/addTrans" ||
      this.$route.path === "/product/archives/model/editTrans"
        ? "trans"
        : "normal";
    if (this.page === "trans") {
      if (this.basicForm[this.basicForm.length - 1].label !== "差异说明") {
        this.basicForm.push({
          label: "差异说明",
          unit: "",
          element: "textarea",
          type: "",
          name: "differenceRemark",
          isRequired: false
        });
      }
    }
  },
  created() {
    this.getDict();
    this.getPdsConfCategoryTree();
    this.getCertSelect();
    this.dataInit();
  },
  computed: {
    ...mapGetters(["elements", "language"])
  },
  watch: {},
  methods: {
    refresh() {
      this.dataInit();
      this.clearValidate();
      if (this.$route.query.modelPbsId) {
        this.modelPbsId = this.$route.query.modelPbsId || this.modelPbsId;
        this.getModelDetail();
        this.clearValidate();
        return;
      }
      if (this.$route.query.plmModelNoMain) {
        this.search.plmModelNoMain =
          this.$route.query.plmModelNoMain || this.search.plmModelNoMain;
        this.modelExtends();
        this.clearValidate();
        return;
      }
    },
    dataInit() {
      const data = {
        pdsFileModelBaseDto: {
          pdsFileModelPbsPicsList: [],
          pdsConfCertCategoryArray: [],
          customerIds: []
        },
        standard: 1,
        pdsFileModelSaleAreasArray: [],
        pdsConfCategoryArray: []
      };
      this.detail = JSON.parse(JSON.stringify(data));
      setTimeout(() => {
        this.$refs.prodfile.dataInit();
      });
    },
    clearValidate() {
      setTimeout(() => {
        this.$refs.basicForm &&
          this.$refs.basicForm.$refs.ruleForm.clearValidate();
      });
    },
    categoryChanged(val) {
      if (val.length === 3) {
        this.$refs.prodfile.prodCategoryChanged(val[2]);
      }
    },
    // 接口获取数据后更新
    refreshDetailCb(res) {
      if (res.code === 200) {
        res.data.pdsFileModelBaseDto.pdsFileModelPbsPicsList =
          res.data.pdsFileModelPbsPicsList;
        res.data.pdsFileModelBaseDto.pdsConfCertCategoryArray = res.data.pdsConfCertCategoryArray.map(
          value => Number(value)
        );
        this.$set(this, "detail", res.data);
        const setMulSelect = str => {
          if (str) {
            let arr = str.split(",");
            arr = arr.map(row => Number(row));
            return arr;
          } else {
            return [];
          }
        };
        let customerNameArr = [];
        if (res.data.pdsFileModelBaseDto.customerNames)
          customerNameArr =
            res.data.pdsFileModelBaseDto.customerNames.split(",") || [];
        customerNameArr.map((item, index) => {
          this.$refs.basicForm.getPdsCustomerByName(item);
        });
        this.$set(
          this.detail.pdsFileModelBaseDto,
          "customerIds",
          setMulSelect(res.data.pdsFileModelBaseDto.customerIds)
        );
        this.$refs.prodfile.refresh(res.data);
      } else {
        this.$message.error(res.message);
      }
    },
    // 新增型号档案导入
    importModel() {
      if (this.search.context) {
        addApi.importModel(this.search).then(res => {
          if (res.code == 200) {
            res.data.pdsFileModelBaseDto.modelPbsId = null;
          }
          this.refreshDetailCb(res);
        });
      }
    },
    // 新增衍生货号档案
    modelExtends() {
      addApi.modelExtends(this.search).then(res => {
        if (res.code == 200) {
          res.data.pdsFileModelBaseDto.modelPbsId = null;
        }
        this.refreshDetailCb(res);
      });
    },
    // 修改档案获取详情
    getModelDetail() {
      addApi
        .modelDetail({
          modelPbsId: this.modelPbsId,
          variation: 0
        })
        .then(res => {
          this.refreshDetailCb(res);
        });
    },
    // 提交或草稿
    async submitForm(type) {
      const basicFormCheck = await this.$refs.basicForm.submitForm();
      const moduleFormRes = await this.$refs.prodfile.submitForm();
      if (!this.detail.pdsConfCategoryArray.length) {
        if (this.page !== "trans") {
          this.$message.error("请选择产品小类");
        } else {
          this.$message.error("请导入产品主型号");
        }
        return;
      }
      if (!basicFormCheck) {
        this.$message.error("请填写完整基本信息");
        return;
      }
      if (type === "save") {
        // 提交
        this.detail.operation = "submit";
        this.detail.status = 2;
        if (!this.detail.pdsFileModelSaleAreasArray.length) {
          this.$message.error("请选择销售国家");
        }
        if (!moduleFormRes.isValid) {
          this.$message.error("请填写完整模组信息");
          return;
        }
        if (!moduleFormRes.data.showFeaturesList.length) {
          this.$message.error("请选择产品特征");
          return;
        }
      }
      this.detail.showAccessoriesList = moduleFormRes.data.showAccessoriesList;
      this.detail.showFeaturesList = moduleFormRes.data.showFeaturesList;
      this.detail.showModules = moduleFormRes.data.showModules;
      this.saveToServer(type);
    },
    saveToServer(type) {
      if (this.loading) return;
      this.loading = true;
      const updataParams = JSON.parse(JSON.stringify(this.detail));
      if (this.page === "trans") {
        updataParams.variation = 1;
      } else {
        updataParams.variation = 0;
      }
      updataParams.pdsFileModelPbsPicsList =
        updataParams.pdsFileModelBaseDto.pdsFileModelPbsPicsList;
      updataParams.pdsConfCertCategoryArray =
        updataParams.pdsFileModelBaseDto.pdsConfCertCategoryArray;
      updataParams.pdsFileModelBaseDto.customerIds = updataParams.pdsFileModelBaseDto.customerIds.join();
      const setModuleData = () => {
        updataParams.showModules.map(moduleItem => {
          if (moduleItem.paramsList && moduleItem.paramsList.length) {
            moduleItem.paramsList.map(paramsItem => {
              paramsItem.paramValue = moduleItem.formData[paramsItem.id];
              paramsItem.paramMaxValue =
                moduleItem.formData[paramsItem.id + "m"];
            });
          }
        });
      };
      setModuleData();
      addApi.saveSuper(updataParams).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.info("保存成功");
          this.refreshDetailCb(res);
          if (type === "save") {
            this.$store.dispatch("delActiveViews");
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 产品小类获取
    getPdsConfCategoryTree() {
      prodApi.getPdsConfCategoryTree().then(res => {
        this.productCategory = res.data;
      });
    },
    // 认证种类
    getCertSelect() {
      prodApi.certSelect().then(res => {
        this.basicForm[9].options = res.data;
      });
    },
    // 获取字典选项
    getDict() {
      const codes = "prod_file_sales_area";
      this.basicForm.forEach(value => {
        if (value.dictCode) {
          baseApi.getTypeValue(value.dictCode).then(res => {
            this.$set(value, "options", res.data.rows);
          });
        }
      });
      baseApi.getTypesValue(codes).then(res => {
        this.countryList = res.data[codes];
        this.countryList.map(row => {
          row.salesAreaDv = row.value;
          return row;
        });
        this.$set(this, "countryList", res.data[codes]);
      });
    }
  }
};
</script>
